package com.frinder.base;

import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;

import static com.frinder.base.ByteBufUtils.buf;

/**
 * @ClassName HeartbeatHandler
 * @Description 心跳检测机制
 * @Author frinder
 * @Date 2018/11/28 18:57
 * @Version 1.0
 */
@Slf4j
public class HeartbeatHandler extends ChannelInboundHandlerAdapter {

    public static final String HB = "Heart Beat!";

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt)
            throws Exception {
        if (evt instanceof IdleStateEvent) {
            log.debug("*** 客户端IP: {}, 超时类型: {}", ctx.channel().remoteAddress(), ((IdleStateEvent) evt).state());
//            ctx.writeAndFlush(buf(HB, DELIMITER)).addListener(ChannelFutureListener.CLOSE_ON_FAILURE);
//            ctx.writeAndFlush(buf(HB)).addListener(ChannelFutureListener.CLOSE_ON_FAILURE);
            ctx.writeAndFlush(buf(HB, "\n")).addListener(ChannelFutureListener.CLOSE_ON_FAILURE);
        } else {
            super.userEventTriggered(ctx, evt);
        }
    }
}